<?php
/**
 * 授权(合同-应用-租户关系)
 * @author daimin 2015-7-24
 */
namespace common\repositories\common;

use pahanini\curl\Multi;
use pahanini\curl\Request;
use Yii;
use linslin\yii2\curl;
use yii\base\InvalidParamException;
use yii\helpers\ArrayHelper;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmApplicationEntity;
use common\entities\common\MyscrmAuthorizeTypeEntity;
use common\entities\common\MyscrmContractEntity;
use common\entities\common\MyscrmFunctionupgradeEntity;
use common\entities\common\MyscrmOrganizationToAuthorizeEntity;
use common\entities\common\MyscrmOrganizationToPackageEntity;
use common\entities\common\MyscrmPackageEntity;
use common\entities\common\MyscrmPackagePriceEntity;
use common\entities\common\MyscrmPackageToApplicationEntity;
use common\support\StringHelper;
use yii\helpers\Json;


class MyscrmAuthorizeRepository extends BaseRepository {

    static $UsedAuthrizeNums = null; // 已使用的授权数

    /**
     * 保存OrganizationToAuthorize
     * @param $organizationId
     * @param $contractId
     * @param $authInfo
     * @throws \Exception
     */
    public function saveOrganizationToAuthorize($organizationId, $contractId, $authInfo)
    {

        /** @var MyscrmApplicationEntity $app */
        $app = MyscrmApplicationEntity::findOne([
            'ApplicationId' => $authInfo['id']
        ]);
        if (empty($app)) {
            throw $this->throwException('应用不存在:' . $authInfo['friendly_name']);
        }

        /** @var MyscrmAuthorizeTypeEntity $authorizeType */
        $authorizeType = $this->getAuthorizeType($app['ApplicationId']);
        if (empty($authorizeType)) {
            throw $this->throwException('应用授权类型不存在:' . $authInfo['friendly_name']);
        }

        $isQdAdvanced = 0;
        if(isset($authInfo['IsQdAdvanced'])) {
            $isQdAdvanced = $authInfo['IsQdAdvanced'];
        }

        /** @var MyscrmOrganizationToAuthorizeEntity $organAuth */
        $organAuth = MyscrmOrganizationToAuthorizeEntity::findOne([
            'OrganizationId' => $organizationId,
            'ApplicationId' => $app->ApplicationId,
            'AuthorizeTypeId' => $authorizeType->AuthorizeTypeId,
            'ContractId' => $contractId,
            'IsQdAdvanced' => $isQdAdvanced,
        ]);

        $totalNum = $authInfo['total_num'] < 0 ? 0 : $authInfo['total_num'];

        if (empty($organAuth)) {
            //插入
            $organAuth = new MyscrmOrganizationToAuthorizeEntity();
            $organAuth->OrganizationId = $organizationId;
            $organAuth->ApplicationId = $app->ApplicationId;
            $organAuth->AuthorizeTypeId = $authorizeType->AuthorizeTypeId;
            $organAuth->ContractId = $contractId;
            $organAuth->Id = StringHelper::uuid();

            //sonar 坏味道修复7

            if(isset($authInfo['IsQdAdvanced'])) {
                $organAuth->IsQdAdvanced = $authInfo['IsQdAdvanced'];
            }

        } else {
            $usedNums = self::getUsedAuthorizeNum($organizationId, true);
            if (!empty($usedNums)) {
                $usedNum = ArrayHelper::getValue($usedNums, $organAuth->Id);
                if ($usedNum > $totalNum) {
                    throw $this->throwException("已经使用授权数不能大于授权总数");
                }
            }
        }

        $organAuth->TotalNum = $totalNum;
        $organAuth->VersionNumber = date("Ymd");

        if (!$organAuth->save()) {
            throw $this->throwException('保存授权失败');
        }

    }
    /**
     * 获取应用的授权类型
     * 目前只支持按授权数授权
     * @param $applicationId string 应用ID
     * @return null|static
     */
    private function getAuthorizeType($applicationId){
        return MyscrmAuthorizeTypeEntity::findOne([
            'UniqueName' => 'projcount',
            'ApplicationId' => $applicationId,
        ]);
    }

    /**
     * 返回指定的orgid的所有授权, 需要app名，package名，授权数，授权时间
     * @param $orgId string 租户ID
     * @param bool $doFilter 是否执行过滤
     * @return array
     */
    public function getAuthorizeAppsByOrgId($orgId, $doFilter=true){
        $orgAuths = MyscrmOrganizationToAuthorizeEntity::findAll([
            "OrganizationId" => $orgId
        ]);
        $appRes = [];
        $appContracts = [];
        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);
        if(!empty($orgAuths)){
            foreach($orgAuths as $orgAuth){
                //需要查询合同，如果合同不存在就不返回app
                if($doFilter && $orgAuth['TotalNum'] <= 0){
                    continue;
                }
                // 拿合同信息
                $contract = MyscrmContractEntity::findOne([
                    "ContractId" => $orgAuth['ContractId'],
                    "OrganizationId" => $orgId,
                ]);

                if(empty($contract)){
                    continue;
                }

                if($doFilter){//过滤掉授权数为0或者已经弃用的合同
                    if(intval($orgAuth['TotalNum']) <= 0 || $contract['Status'] != 1 || MyscrmContractEntity::isContractOverdue($contract)){
                        continue;
                    }
                }

                $appInfo = $this->getAppInfo($orgAuth);
                if(!empty($appInfo)){

                    $uniqueName = $appInfo['UniqueName'];
                    if($doFilter){
                        if(isset($appContracts[$uniqueName])){
                            $appContracts[$uniqueName] []= $contract;
                        }else{
                            $appContracts[$uniqueName] = [$contract];
                        }
                    }

                    if(isset($appRes[$uniqueName])){
                        $appRes[$uniqueName]['total_num'] += intval($appInfo['total_num']);
                    }else{
                        // 判断app中的移动销售是否是高级版
                        if($uniqueName == MyscrmApplicationEntity::YDXS){
                            if(!$isAdv){
                                $appInfo['FriendlyName'] = MyscrmApplicationEntity::LOW_VERSION_YDXS;
                            }
                        }
                        $appRes[$uniqueName] = $appInfo;
                        $appRes[$uniqueName]['total_num'] = intval($appInfo['total_num']);
                    }
                }
            }
        }
        if($doFilter){ // 过滤掉没有合同的应用
            foreach($appRes as $code=>$info){
                if(!isset($appContracts[$code]) || count($appContracts[$code]) <= 0){
                    unset($appRes[$code]);
                }
            }
        }


        return $appRes;
    }

    /**
     * 获取app状态
     * @param $orgAuth object 授权实体
     * @return array|void
     */
    private function getAppInfo($orgAuth){
        $app = MyscrmApplicationEntity::findOne([
            "ApplicationId" => $orgAuth['ApplicationId'],
        ]);
        if(empty($app)){
            return null;
        }
        $appInfo = $app->toArray();
        $appInfo['total_num'] =  $orgAuth['TotalNum'];
        $pkgToApp = MyscrmPackageToApplicationEntity::findOne([
            "application_id" => $appInfo['ApplicationId']
        ]);
        if(!empty($pkgToApp)){
            $pkg = MyscrmPackageEntity::findOne([
                "id" => $pkgToApp['package_id']
            ]);
            if(!empty($pkg)){
                $appInfo['package'] = $pkg->toArray();
            }
        }
        return $appInfo;
    }

    /**
     * 根据app的uniqueName获取app的授权信息
     * @param $orgId
     * @param $uniqueName
     * @return array|null
     */
    public function getAuthorizeAppByAppUniqueName($orgId, $uniqueName){
        $app = MyscrmApplicationEntity::findOne([
            "UniqueName" => $uniqueName
        ]);
        $appInfo = null;
        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);
        if(!empty($app)){
            $orgAuths = MyscrmOrganizationToAuthorizeEntity::findAll([
                "OrganizationId" => $orgId,
                "ApplicationId" => $app['ApplicationId']
            ]);

            $appInfo = $app->toArray();
            if(!$isAdv && $appInfo['UniqueName'] == MyscrmApplicationEntity::YDXS){
                $appInfo['FriendlyName'] = MyscrmApplicationEntity::LOW_VERSION_YDXS;
            }
            $appInfo['contracts'] = [];
            foreach($orgAuths as $orgAuth){

                // 拿合同信息
                $contract = MyscrmContractEntity::findOne([
                    "ContractId" => $orgAuth['ContractId'],
                    "OrganizationId" => $orgId,
                ]);

                if(!empty($contract)){
                    $contract = $contract->toArray();
                    $contract['authorize_id'] = $orgAuth['Id'];
                    $contract['authorize_type_id'] = $orgAuth['AuthorizeTypeId'];

                    $contract['total_num'] = intval($orgAuth['TotalNum']);

                    if(isset($appInfo['total_num'])){
                        $appInfo['total_num'] += intval($orgAuth['TotalNum']);
                    }else{
                        $appInfo['total_num'] = intval($orgAuth['TotalNum']);
                    }

                    array_push($appInfo['contracts'], $contract);
                }

            }
        }

        return $appInfo;
    }
    /**
     * 根据app的uniqueName获取一条授权信息
     * @param $orgId
     * @param $uniqueName
     * @return MyscrmOrganizationToAuthorizeEntity|array
     */
    public function getOneAuthorizeByAppUniqueName($orgId, $appId , $isQdAdvanced){
        return MyscrmOrganizationToAuthorizeEntity::find()
            ->where(["ApplicationId" => $appId])
            ->andWhere(["OrganizationId" => $orgId])
            ->andFilterWhere(["IsQdAdvanced" => $isQdAdvanced])
            ->one();
    }
    /**
     * 获取旧租户的包定义
     * @return array
     */
    private function getOldOrgDefine(){
        return [
            '渠道管家' => ['unique_name' => MyscrmPackageEntity::QDGJ, 'friendly_name' => '渠道管家', 'total_num' =>0, 'applications_info' =>[],
                'applications' => [MyscrmApplicationEntity::XMF, MyscrmApplicationEntity::QMYX]],
            '移动销售' => ['unique_name' => MyscrmPackageEntity::YDXS, 'friendly_name' => '移动销售', 'total_num' =>0, 'applications_info' =>[],
                'applications' => [MyscrmApplicationEntity::YDXS]],
            'O2O应用' => ['unique_name' => MyscrmPackageEntity::O2OYY, 'friendly_name' => 'O2O应用', 'total_num' =>0, 'applications_info' =>[],
                'applications' => [MyscrmApplicationEntity::WLS_NEW, MyscrmApplicationEntity::WLS]],
            '旺财宝' => ['unique_name' => MyscrmPackageEntity::WCB, 'friendly_name' => MyscrmPackageEntity::WCB_ZH, 'total_num' =>0, 'applications_info' =>[],
                'applications' => [MyscrmApplicationEntity::WCB]],
        ];
    }

    /**
     * 获取老租户的授权package
     * @param $orgId string 租户ID
     * @param $$useCurl bool 是否远程
     * @return array
     */
    private function getOldOrgAuthorizePackagesByOrgId($orgId, $useCurl=false){
        $pkgs = $this->getOldOrgDefine();
        $pkgsRes = [];
        if($useCurl){
            $usedNums = MyscrmAuthorizeRepository::getUsedAuthorizeNum($orgId, true);
        }

        foreach($pkgs as $pname => $pkg){
            foreach($pkg['applications'] as $appcode){
                $app = MyscrmApplicationEntity::findOne([
                    'UniqueName' => $appcode
                ]);

                if(!empty($app)){
                    $appinfo = $app->toArray();
                    $pkg['applications_info'][$app['UniqueName']] = $appinfo;
                    $pkg['applications_info'][$app['UniqueName']]['total_num'] = 0;
                    $pkg['applications_info'][$app['UniqueName']]['used_num'] = 0;
                    $orgAuths = MyscrmOrganizationToAuthorizeEntity::findAll([
                        "ApplicationId" => $app['ApplicationId'],
                        "OrganizationId" => $orgId,
                    ]);
                    foreach($orgAuths as $orgAuth){
                        if($orgAuth['TotalNum'] <= 0){
                            continue;
                        }
                        $contract = MyscrmContractEntity::findOne([
                            'ContractId' => $orgAuth['ContractId']
                        ]);
                        if(empty($contract) || $contract['Status'] != 1 || MyscrmContractEntity::isContractOverdue($contract)){
                            continue;
                        }
                        $pkg['applications_info'][$app['UniqueName']]['total_num'] += $orgAuth['TotalNum'];
                        if($useCurl){
                            $pkg['applications_info'][$app['UniqueName']]['used_num'] += intval(ArrayHelper::getValue($usedNums, $orgAuth['Id']));
                        }

                    }
                    if($pkg['applications_info'][$app['UniqueName']]['total_num'] <= 0){
                        unset($pkg['applications_info'][$app['UniqueName']]);
//                            unset($pkg['applications'][array_search($app['UniqueName'], $pkg['applications'])]);
//                            unset($pkg['applications'][$app['UniqueName']]);
                        foreach($pkg['applications'] as $k=>$v){
                            if($v == $app['UniqueName']){
                                unset($pkg['applications'][$k]);
                            }
                        }
                    }
                }
            }

            $pkgsRes[$pname] = $pkg;
        }

        $ydxsOrQmyxNum = 0;
        $ydxsOrQmyxUseNum = 0;
        foreach($pkgsRes as $kname => $pkg){
            if($ydxsOrQmyxNum == 0){
                foreach($pkg['applications_info'] as $k => $v){
                    if($k == MyscrmApplicationEntity::QMYX || $k == MyscrmApplicationEntity::YDXS){
                        $ydxsOrQmyxNum = $v['total_num'];
                        $ydxsOrQmyxUseNum = $v['used_num'];
                        break;
                    }
                }
            }
        }

        if($ydxsOrQmyxNum > 0){ //只要有移动销售或者全民营销，那么就要加上所有的免费模块，现在有两个免费模块：小蜜蜂和微楼书新版
            $tarAppCode = MyscrmApplicationEntity::WLS_NEW;
            if(!in_array($tarAppCode, $pkgsRes['O2O应用']['applications'])){
                $pkgsRes['O2O应用']['applications'] []= $tarAppCode;
                $appWlcNew = MyscrmApplicationEntity::findOne([
                    "UniqueName" => $tarAppCode
                ]);
                $appWlcNew = $appWlcNew->toArray();
                $appWlcNew['total_num'] = $ydxsOrQmyxNum;
                $appWlcNew['used_num'] = $ydxsOrQmyxUseNum;
                $pkgsRes['O2O应用']['applications_info'][$tarAppCode] = $appWlcNew;
            }
            $tarAppCode = MyscrmApplicationEntity::XMF;
            if(!in_array($tarAppCode, $pkgsRes['渠道管家']['applications'])){
                $pkgsRes['渠道管家']['applications'] []= $tarAppCode;
                $appXmf = MyscrmApplicationEntity::findOne([
                    "UniqueName" => $tarAppCode
                ]);
                $appXmf = $appXmf->toArray();
                $appXmf['total_num'] = $ydxsOrQmyxNum;
                $appXmf['used_num'] = $ydxsOrQmyxUseNum;
                $pkgsRes['渠道管家']['applications_info'][$tarAppCode] = $appXmf;
            }
        }


        foreach($pkgsRes as $kname => $pkg){
            $newApps = [];
            foreach($pkg['applications'] as $k => $v){
                if(isset($pkg['applications_info'][$v])){
                    $newApps [] = $v;
                }
            }
            $pkg['applications'] = $newApps;
            $pkg['applications_info'] = array_values($pkg['applications_info']);
            $pkgsRes[$kname] = $pkg;
        }

        return $pkgsRes;
    }


    /**
     * 返回指定的orgid的所有授权, 需要app名，package名，授权数，授权时间
     * @param $orgId string 租户Id
     * @param bool|true $useCurl 是否使用curl来进行远程数据获取
     * @param bool|true $doFilter 是否进行过滤，用来过滤掉废弃、过期合同，没有授权的合同和app
     * @param bool|false $returnAll 是否返回所有的套餐包
     * @return array
     * @throws \Exception
     */
    public function getAuthorizePackagesByOrgId($orgId, $useCurl=true, $doFilter=true, $returnAll=false){
        if(!MyscrmFunctionupgradeEntity::checkIs810Version($orgId)){ //如果是老租户
             return $this->getOldOrgAuthorizePackagesByOrgId($orgId, $useCurl);
        }

        $orgPkgs = MyscrmOrganizationToPackageEntity::findAll([
            "organization_id" => $orgId
        ]);

        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);
        $pkgRes = [];
        if(!empty($orgPkgs)){
            if($useCurl){
                $usedNums = MyscrmAuthorizeRepository::getUsedAuthorizeNum($orgId, true);
            }
            foreach($orgPkgs as $orgPkg){
                $pkg = MyscrmPackageEntity::findOne([
                    "id" => $orgPkg['package_id']
                ]);
                if(!empty($pkg)){
                    $pkgInfo = $pkg->toArray();
                    $pkgToApps = MyscrmPackageToApplicationEntity::findAll([ // 一个包有哪些应用
                        "package_id" => $orgPkg['package_id']
                    ]);

                    if(!empty($pkgToApps) && count($pkgToApps) > 0){
                        $pkgInfo['total_num'] = 0;
                        $pkgInfo['applications'] = [];
                        $pkgInfo['applications_info'] = [];
                        $pkgInfo['price'] = MyscrmPackagePriceEntity::getPackagePrice($pkgInfo['id']);
                        if($useCurl){
                            $pkgInfo['used_num'] = 0;
                        }
                        foreach($pkgToApps as $pkgToApp){ // 遍历包中的应用

                            if($doFilter){ //过滤 合同不存在，合同以废弃或过期
                                $contract = MyscrmContractEntity::findOne([
                                    'ContractId' => $orgPkg['contract_id'],
                                    'OrganizationId' => $orgId,
                                ]);
                                if(empty($contract) || $contract['Status'] != 1 || MyscrmContractEntity::isContractOverdue($contract)){
                                    continue;
                                }
                            }

                            $orgAuths = MyscrmOrganizationToAuthorizeEntity::findAll([ //找到授权
                                "ApplicationId" => $pkgToApp['application_id'],
                                "OrganizationId" => $orgId,
                                "ContractId" => $orgPkg['contract_id']
                            ]);

                            $app = MyscrmApplicationEntity::findOne([
                                "ApplicationId" => $pkgToApp['application_id']
                            ]);
                            if(!empty($app)){
                                $appinfo = $app->toArray();
                                $appinfo['total_num'] = 0;
                                if($useCurl){
                                    $appinfo['used_num'] = 0;
                                }
                                if(!$isAdv && $appinfo['UniqueName'] == MyscrmApplicationEntity::YDXS){
                                    $appinfo['FriendlyName'] = MyscrmApplicationEntity::LOW_VERSION_YDXS;
                                }
                            }else{
                                continue; //不存在该应用就continue
                            }

                            if(!empty($orgAuths)){
                                foreach($orgAuths as $orgAuth){ //遍历授权
                                    if($doFilter){  //过滤，如果授权数小于等于0，就过掉
                                        if(intval($orgAuth['TotalNum']) <= 0){
                                            continue;
                                        }
                                    }
                                    if(!empty($appinfo)){
                                        $appinfo['total_num'] = intval($orgAuth['TotalNum']);
                                    }
                                    if($useCurl && !empty($usedNums)){
                                        if(!empty($appinfo)){
                                            $appinfo['used_num'] = intval(ArrayHelper::getValue($usedNums, $orgAuth['Id']));
                                        }
                                    }
                                }

                                if(!isset($pkgRes[$pkgInfo['friendly_name']])){
                                    $pkgRes[$pkgInfo['friendly_name']] = $pkgInfo;
                                }

                                if(!empty($appinfo)){
                                    $pkgRes[$pkgInfo['friendly_name']]['applications'] []= $appinfo['UniqueName'];
                                    $pkgRes[$pkgInfo['friendly_name']]['applications'] = array_unique($pkgRes[$pkgInfo['friendly_name']]['applications']);

                                    if(isset($pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']])){
                                        $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']]['total_num'] += $appinfo['total_num'];
                                        if($useCurl){
                                            $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']]['used_num'] += $appinfo['used_num'];
                                        }
                                    }else{
                                        $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']] = $appinfo;
                                    }

                                    $appTotalNum = $pkgRes[$pkgInfo['friendly_name']]['total_num'];
                                    $preAppTotalNum = $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']]['total_num'];
                                    if($preAppTotalNum > $appTotalNum){
                                        $pkgRes[$pkgInfo['friendly_name']]['total_num'] = $preAppTotalNum;
                                    }

                                    if($useCurl){
                                        // 由于App的已绑定授权数会有所不同导致我这里已绑定授权会不准确，我这里取包下面的app的最大已用授权作为包的已绑定授权
                                        $appUsedNum = $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']]['used_num'];
                                        if($appUsedNum > $pkgRes[$pkgInfo['friendly_name']]['used_num']){
                                            $pkgRes[$pkgInfo['friendly_name']]['used_num'] = $pkgRes[$pkgInfo['friendly_name']]['applications_info'][$appinfo['UniqueName']]['used_num'];
                                        }
                                    }

                                }
                            }

                        }

                    }
                }

            }
        }

        $pkgResNew = [];
        if($isAdv){
            $pkgRes[MyscrmPackageEntity::YDXS_ZH]['applications_info'][MyscrmApplicationEntity::YDXS] =
                $pkgRes[MyscrmPackageEntity::ZSSLC_ZH]['applications_info'][MyscrmApplicationEntity::YDXS];
            $pkgRes[MyscrmPackageEntity::YDXS_ZH]['total_num'] = $pkgRes[MyscrmPackageEntity::ZSSLC_ZH]['total_num'];
        }

        foreach($pkgRes as $pkgName => $pkgInfo){
            $pkgInfo['applications_info'] = array_values($pkgInfo['applications_info']);
            if(!$returnAll){
                if(!$isAdv && $pkgInfo['unique_name'] == MyscrmPackageEntity::YDXS){ //如果租户没有购买移动销售高级版，则不要返回移动销售这个包
//                $pkgInfo['total_num'] = 0;
//                $pkgInfo['applications_info'] = [];
//                $pkgInfo['applications'] = [];
                    continue;
                }
                if($pkgInfo['total_num'] <= 0){
                    continue;
                }
            }else{
                if(!$isAdv && $pkgInfo['unique_name'] == MyscrmPackageEntity::YDXS){ //如果租户没有购买移动销售高级版，则不要返回移动销售这个包
                    $pkgInfo['total_num'] = 0;
                    $pkgInfo['used_num'] = 0;
                    $pkgInfo['applications_info'] = [];
                    $pkgInfo['applications'] = [];
                }
            }

            if($isAdv && $pkgInfo['unique_name'] == MyscrmPackageEntity::ZSSLC){
                $appcodes = $pkgInfo['applications'];
                $appinfos = $pkgInfo['applications_info'];
                $pkgInfo['applications'] = [];
                $pkgInfo['applications_info'] = [];
                foreach($appcodes as $appcode){
                    if($appcode != MyscrmApplicationEntity::YDXS){
                        $pkgInfo['applications'] []= $appcode;
                    }
                }

                foreach($appinfos as $appinfo){
                    if($appinfo['UniqueName'] != MyscrmApplicationEntity::YDXS){
                        $pkgInfo['applications_info'] []= $appinfo;
                    }
                }

            }

            $pkgResNew[$pkgName] = $pkgInfo;
        }
        return $pkgResNew;
    }

    /**
     * 返回指定的orgid的所有授权, 需要app名，package名，授权数，授权时间, 不进行远程curl，所以没有used_num
     * @param $orgId string 租户ID
     * @return array
     * @throws \Exception
     */
    public function getAuthorizePackagesByOrgIdNoCurl($orgId){
        return $this->getAuthorizePackagesByOrgId($orgId, false);
    }


    /**
     * 获取已授权数
     * @param $orgcode string 授权码
     * @param $firstIsOrgId bool true表示第一个参数是orgId
     * @return array [[AuthorizeId=>count],...]
     * @throws \Exception
     */
    public static function getUsedAuthorizeNum($orgcode, $firstIsOrgId=false){
        if(self::$UsedAuthrizeNums == null){
            $curl = new curl\Curl();

            $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
            if(empty($appCfg)){
                throw new \Exception("找不到获取已授权数的远程接口配置");
            }

            if($firstIsOrgId){
                $org = MyscrmOrganizationRepository::getById($orgcode);
                if(empty($org)){
                    throw new \Exception("不存在的租户");
                }
                $orgcode = $org['UniqueName'];
            }
            $appsecret = $appCfg['appSecret'];
            $nowtimestamp = time();
            $sign = md5($nowtimestamp."#".$appsecret);
            $siteUrl = rtrim($appCfg['url'], '/');
            $param = [
                'r' => 'project-auth/get-all-authorize-count',
                'appid' => $appCfg["appId"],
                't' => $nowtimestamp,
                'sign' => $sign,
                'orgcode' => $orgcode,
            ];
            $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
            if($res['retCode'] == 0)
            {
                $usedNums = $res['data'];
                $result = [];
                if(!empty($usedNums)){
                    foreach($usedNums as $usedNum){
                        $result[$usedNum['AuthorizeId']] = intval($usedNum['count']);
                    }
                }
                self::$UsedAuthrizeNums = $result;
            }
        }

        return self::$UsedAuthrizeNums;

    }

    /**
     * 通过租户id和合同id得到授权信息
     * @param $orgId string 租户ID
     * @param $contractId string 合同ID
     * @return static[]
     */
    public function getOrganizationToAuthorizesByOrgIdAndContractId($orgId, $contractId){
         return MyscrmOrganizationToAuthorizeEntity::findAll([
             "OrganizationId" => $orgId,
             "ContractId" => $contractId
         ]);
    }

    /**
     * 拿到授权总数
     * @param $authorizeId string 授权ID
     * @return int
     */
    public function getAuthorizeTotalNum($authorizeId){
        $auth = MyscrmOrganizationToAuthorizeEntity::findOne([
            'Id' => $authorizeId
        ]);
        if(!empty($auth)){
            return $auth['TotalNum'];
        }
        return 0;
    }

    /**
     * 得到指定的授权ID的包下的兄弟app的授权ID
     * @param $orgId string 租户ID
     * @param $authorizeId string 授权ID
     * @return array
     * @throws \Exception
     */
    public function getAuthorizePackageAppBrothersAuthorId($orgId, $authorizeId){
        $auth = MyscrmOrganizationToAuthorizeEntity::findOne([
            "Id" => $authorizeId
        ]);
        if(empty($auth)){
            throw $this->throwException("不存在的授权");
        }

        $contract = MyscrmContractEntity::findOne([
            'OrganizationId' => $orgId,
            'ContractId' => $auth['ContractId']
        ]);

        if(empty($contract)){
            throw $this->throwException("合同不存在");
        }

        if($contract['Status'] != 1 || strtotime($contract['EndOn']) < time()){
            throw $this->throwException("合同已过期或废弃");
        }

        $appGetPkg = MyscrmApplicationEntity::findOne([
            "ApplicationId" => $auth['ApplicationId']
        ]);

        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);

        if($appGetPkg['UniqueName'] == MyscrmApplicationEntity::YDXS){ // 如果当前app是移动销售，那么其包根据是否购买移动销售高级版有所不同
            if($isAdv){
                $pkg = MyscrmPackageEntity::findOne([
                    "unique_name" => MyscrmPackageEntity::YDXS
                ]);
            }else{
                $pkg = MyscrmPackageEntity::findOne([
                    "unique_name" => MyscrmPackageEntity::ZSSLC
                ]);
            }

        }else{
            //拿到包
            $pkgToapp = MyscrmPackageToApplicationEntity::findOne([
                'application_id' => $auth['ApplicationId']
            ]);
            if(empty($pkgToapp)){
                throw $this->throwException("不存在的套餐包与应用的关系");
            }

            $pkg = MyscrmPackageEntity::findOne([
                'id' => $pkgToapp['package_id']
            ]);
        }

        if(empty($pkg)){
            throw $this->throwException("不存在的套餐包");
        }

        $pkgInfo = $pkg->toArray();
        $pkgToapps = MyscrmPackageToApplicationEntity::findAll([
            'package_id' => $pkgInfo['id'],
        ]);

        $pkgInfo['applications'] = [];

        if(!$isAdv && $pkgInfo['unique_name'] == MyscrmPackageEntity::YDXS){ // 如果没有购买移动销售高级版则移动高级版不返回app
             return $pkgInfo;
        }
        foreach($pkgToapps as $pkgToapp){
            $app = MyscrmApplicationEntity::findOne([
                "ApplicationId" => $pkgToapp['application_id']
            ]);

            if(!empty($app)){
                //如果购买了移动销售高级版，则不在掌上售楼处中返回移动跟客
                if($isAdv && $pkgInfo['unique_name'] == MyscrmPackageEntity::ZSSLC && $app['UniqueName'] == MyscrmApplicationEntity::YDXS){
                     continue;
                }
                $authNew = MyscrmOrganizationToAuthorizeEntity::findOne([
                    "ApplicationId" => $app['ApplicationId'],
                    "ContractId" => $auth['ContractId'],
                    "OrganizationId" => $orgId
                ]);
                if(!empty($authNew)){
                    $pkgInfo['applications'][$app['UniqueName']] = $authNew['Id'];
                }

            }
        }

        return $pkgInfo;

    }

    /**
     * 获取老租户的package
     * @return array
     */
    public function getOldOrgPackagesByOrgName(){
        $pkgs = $this->getOldOrgDefine();
        $pkgsRes = [];
        foreach($pkgs as $pname => $pkg) {
            foreach ($pkg['applications'] as $appcode) {
                $app = MyscrmApplicationEntity::findOne([
                    'UniqueName' => $appcode
                ]);

                if(!empty($app)){
                    $appinfo = $app->toArray();
                    $pkg['applications_info'][$app['UniqueName']] = $appinfo;
                    $pkg['applications_info'][$app['UniqueName']]['total_num'] = 0;
                }
            }
            $pkgsRes[$pname] = $pkg;
        }

        foreach($pkgsRes as $kname => $pkg){
            $newApps = [];
            foreach($pkg['applications'] as $k => $v){
                if(isset($pkg['applications_info'][$v])){
                    $newApps [] = $v;
                }
            }
            $pkg['applications'] = $newApps;
            $pkg['applications_info'] = array_values($pkg['applications_info']);
            $pkgsRes[$kname] = $pkg;
        }

        return $pkgsRes;
    }


    /**
     * 获取包的授权数
     * @param $orgId
     * @param $packageId
     * @return array
     * @throws \Exception
     */
    public function getPackageTotalNum($orgId, $packageId){
        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);

        $pkg = MyscrmPackageEntity::findOne([
            "id" => $packageId
        ]);
        if(empty($pkg)){
            throw $this->throwException("不存在的包");
        }
        if(!$isAdv && $pkg['unique_name'] == MyscrmPackageEntity::YDXS){
            return 0;
        }
        $pkgInfo = $pkg->toArray();
        $pkgToApps = MyscrmPackageToApplicationEntity::findAll([
            "package_id" => $packageId
        ]);
        foreach($pkgToApps as $pkgToApp){
            $pkgInfo['total_num'] = 0;
            $totalNum = 0;
            $orgToAuths = MyscrmOrganizationToAuthorizeEntity::findAll([
                "OrganizationId" => $orgId,
                "ApplicationId" => $pkgToApp['application_id']
            ]);
            $now = date("Y-m-d H:i:s");
            foreach($orgToAuths as $orgToAuth){
                // 需要检查一下合同，是否过期，是否废弃
                $contract = MyscrmContractEntity::find()->where([
                    'OrganizationId' => $orgId, 'ContractId' => $orgToAuth['ContractId'], 'Status' => 1
                ])->andWhere(['>', 'EndOn', $now])->one();
                if(empty($contract)){
                    continue;
                }
                $totalNum += $orgToAuth['TotalNum'];
            }

            if($totalNum > $pkgInfo['total_num']){
                $pkgInfo['total_num'] = $totalNum;
            }

        }

        return  $pkgInfo['total_num'];

    }


    /**
     * 根据包名获取包的授权数
  * @param $orgId
     * @param $packageName
     * @return array
     * @throws \Exception
     */
    public function getPackageTotalNumByName($orgId, $packageName){
        $pkg = MyscrmPackageEntity::findOne([
            "unique_name" => $packageName
        ]);
        if(empty($pkg)){
            throw $this->throwException("不存在的包");
        }
        return $this->getPackageTotalNum($orgId, $pkg['id']);
    }

    /**
     * 得到包的某个合同的授权ID
     * @param $orgId
     * @param $packageId
     * @param $contractId
     * @return int
     */
    public function getPackageTotalNumInContract($orgId, $packageId, $contractId){

        $isAdv = MyscrmFunctionupgradeEntity::isAdvancedVersionYdxs($orgId);
        $pkg = MyscrmPackageEntity::findOne([
            "id" => $packageId
        ]);
        if(empty($pkg)){
            return 0;
        }
        if(!$isAdv && $pkg['unique_name'] == MyscrmPackageEntity::YDXS){
            return 0;
        }
        $now = date("Y-m-d H:i:s");
        $contract = MyscrmContractEntity::find()->where([
            'OrganizationId' => $orgId, 'ContractId' => $contractId, 'Status' => 1
        ])->andWhere(['>', 'EndOn', $now])->one();
        if(empty($contract)){
            return 0;
        }

        $pkgToApps = MyscrmPackageToApplicationEntity::findAll([
            "package_id" => $packageId
        ]);
        $totalNum = 0;
        foreach($pkgToApps as $pkgToApp){
            // 需要检查一下合同，是否过期，是否废弃
            $orgToAuth = MyscrmOrganizationToAuthorizeEntity::findOne([
                "OrganizationId" => $orgId,
                "ApplicationId" => $pkgToApp['application_id'],
                "ContractId" => $contractId
            ]);
            if(!empty($orgToAuth)){
                if($orgToAuth['TotalNum'] > $totalNum){
                    $totalNum = $orgToAuth['TotalNum'];
                }
            }
        }
        return $totalNum;
    }

    /**
     * 获取租户是否有绑定旧版微楼书
     * @param $orgCode
     * @param $appCode
     * @return bool|int
     * @throws \Exception
     */
    public static function hasBindApplication($orgCode, $appCode)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if (empty($appCfg)) {
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp . "#" . $appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/has-bind-application',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'appCode' => $appCode,
        ];
        $res = self::curlGet($curl, $siteUrl . '?' . http_build_query($param));

        if ($res['retCode'] == 0) {
            return $res['data'];
        }

        return false;
    }

    /**
     * 获取已授权项目总数
     * @param $orgcode string 授权码
     * @param $firstIsOrgId bool true表示第一个参数是orgId
     * @return null
     * @throws \Exception
     */
    public static function getProjectBindAppNum($orgcode, $firstIsOrgId=false){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        if($firstIsOrgId){
            $org = MyscrmOrganizationRepository::getById($orgcode);
            if(empty($org)){
                throw new \Exception("不存在的租户");
            }
            $orgcode = $org['UniqueName'];
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-bind-app-num',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgcode,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));

        if($res['retCode'] == 0)
        {
            return intval($res['data']);
        }

        return false;
    }

    /**
     * 获取租户授权ID，对应绑定的项目ID列表
     * @param $orgcode
     * @param bool|false $firstIsOrgId
     * @return bool|int
     * @throws \Exception
     */
    public static function getProjectIds($orgcode, $firstIsOrgId=false){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        if($firstIsOrgId){
            $org = MyscrmOrganizationRepository::getById($orgcode);
            if(empty($org)){
                throw new \Exception("不存在的租户");
            }
            $orgcode = $org['UniqueName'];
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-ids',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgcode,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 根据orgId获取所有授权
     * @param string $orgId 租户Id
     * @return array|MyscrmAuthorizeTypeEntity[]
     */
    public function getAuthorizeListByOrgId($orgId){
        return MyscrmOrganizationToAuthorizeEntity::findAll(['OrganizationId' => $orgId]);
    }

    /**
     * 获取租户授权ID，对应绑定的项目ID列表
     * @param $orgCode
     * @param $keyword
     * @param string $contractId
     * @param string $projectId
     * @return array
     * @throws \Exception
     */
    public static function getNeedRenewedProjects($orgCode, $keyword, $contractId = '', $projectId = '')
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-need-renewed-projects',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'keyword' => $keyword,
            'contractId' => $contractId,
            'projectId' => $projectId,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getAllProjectsForRenewed($orgCode, $keyword)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-all-projects-for-renewed',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'keyword' => $keyword,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getNeedRenewContractList($orgCode)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-need-renewed-contract-list',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 获取项目禁用/已禁用列表
     * @param $orgCode
     * @param int $status
     * @param string $projectName
     * @param int $pageIndex
     * @param int $pageSize
     * @return bool|int
     * @throws \Exception
     */
    public static function getProjectAuthContractList($orgCode, $projectName = '', $status = 0, $pageIndex = 1, $pageSize = 10){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-auth-contract-list',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'pageIndex' => $pageIndex,
            'pageSize' => $pageSize,
            'projName' => $projectName,
            'status' => $status
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 更改禁用状态
     * @param $orgCode 需要禁用或者开启的租户code
     * @param $disableItems 需要禁用或者开启的数组
     * @return bool
     * @throws \Exception
     */
    public static function changeDisable($orgCode, $disableItems)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if (empty($appCfg)) {
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp . "#" . $appsecret);
        $siteUrl = rtrim($appCfg['url'], '/') . '?r=project-auth/change-disable';

        $disableItems = json_encode($disableItems);
        $param = [
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'disableItems' => $disableItems,
        ];

        $curl->setOption(CURLOPT_POSTFIELDS, http_build_query($param));
        $res = self::curlPost($curl, $siteUrl);
        if ($res['retCode'] == 0) {
            return true;
        } else {
            return $res['retMsg'];
        }
    }

    public static function getNewestReason($orgCode, $p_projectId, $applicationCode){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-newest-reason',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'projectId' => $p_projectId,
            'application_code' => $applicationCode,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getListByProjectIdApplicationCode($orgCode, $p_projectId, $applicationCode){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-list-by-project-id-application-code',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'projectId' => $p_projectId,
            'application_code' => $applicationCode,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getOverdueOr30daysOverdueContracts($orgName){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-overdue-or30days-overdue-contracts',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getApplicationAuthInfo($orgName, $contractId){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-application-auth-info',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'contract_id' => $contractId,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 获取指定的应用
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getApplicationListByApplicationCodes()
    {
        $applicationCodes = ['5020', '5021', '5003', '5008', '5002', '5030', '5001'];
        return MyscrmApplicationEntity::find()
            ->where(['IN','UniqueName',$applicationCodes])
            ->andWhere(['IsUnAuth' => 0])
            ->orderBy('OrderBy desc')
            ->asArray()
            ->all();
    }

    public static function getProjectApplicationRelation($orgName, $projects){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/') . '?r=project-auth/get-project-application-relation';
        $param = [
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'projects' => $projects,
        ];
        $curl->setOption(CURLOPT_POSTFIELDS, http_build_query($param));
        $res = self::curlPost($curl, $siteUrl);
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function getApplicationToProjectToAuthorizes($orgName, $contractId){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/application-to-project-to-authorize-by-contract-id',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'contract_id' => $contractId,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    public static function SaveBindingAuth($orgName, $auth){
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/') . '?r=project-auth/save-binding-auth';
        $param = [
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'auth' => $auth,
        ];
        $curl->setOption(CURLOPT_POSTFIELDS, http_build_query($param));
        $res = self::curlPost($curl, $siteUrl);
        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 根据合同ID应用代码获取项目绑定记录
     * @param $orgName
     * @param $contractId
     * @param $applicationCode
     * @param $keyword
     * @param $pageIndex
     * @param $pageSize
     * @param $isQdAdvanced
     * @return bool
     * @throws \Exception
     */
    public static function getProjectBindRecordByContractIdApplicationCode($orgName, $contractId, $applicationCode, $keyword, $pageIndex, $pageSize, $isQdAdvanced)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-bind-record-by-contract-id-application-code',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'contractId' => $contractId,
            'applicationCode' => $applicationCode,
            'isQdAdvanced' => $isQdAdvanced,
            'keyword' => $keyword,
            'pageIndex' => $pageIndex,
            'pageSize' => $pageSize,
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));

        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * @param $orgName
     * @param $authorizeId
     * @return bool|array
     * @throws \Exception
     */
    public static function getProjectByAuthorizeId($orgName, $authorizeId)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-by-authorize-id',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'authorizeId' => $authorizeId
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));

        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * @param $orgName
     * @param $projectId
     * @param $applicationCode
     * @return array|bool
     * @throws \Exception
     */
    public static function getProjectIsDisableAndReason($orgName, $projectId, $applicationCode)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-project-is-disable-and-reason',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName,
            'projectId' => $projectId,
            'applicationCode' => $applicationCode
        ];
        $res = self::curlGet($curl, $siteUrl.'?'.http_build_query($param));

        if($res['retCode'] == 0)
        {
            return $res['data'];
        }

        return false;
    }

    /**
     * 获取项目应用合同关系数据
     * @param $orgName
     * @return array|bool
     * @throws \Exception
     */
    public static function getContractApplicationProject($orgName)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp."#".$appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r' => 'project-auth/get-contract-application-project',
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgName
        ];

        $url = $siteUrl . '?' . http_build_query($param);

        $res = self::curlGet($curl, $url);

        if($res && $res['retCode'] == 0)
        {
            return $res['data'];
        }

        return [];
    }

    public static function batchGetContractApplicationProject($orgCodes)
    {
        if(empty($orgCodes)){
            return [];
        }
        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        $nowtimestamp = time();
        $siteUrl = rtrim($appCfg['url'], '/');

        $multi = new Multi();
        $multi->stackSize = count($orgCodes);

        $requests= [];
        foreach ($orgCodes as $orgCode){
            $param = [
                'r' => 'project-auth/get-contract-application-project',
                'appid' => $appCfg["appId"],
                't' => $nowtimestamp,
                'sign' => md5($nowtimestamp."#".$appCfg['appSecret']),
                'orgcode' => $orgCode
            ];
            $url = $siteUrl . '?' . http_build_query($param);

            //echo $url, PHP_EOL;

            $requests[$orgCode] = new Request();
            $requests[$orgCode]->setUrl($url);

            $multi->add($requests[$orgCode]);
        }

        $multi->execute();

        $result = [];
        foreach ($requests as $orgCode => $request) {
            $response = $request->getResponse();
            /* @var $response \pahanini\curl\Response */
            if($res = $response->getContent()){
                $data = json_decode($res, true);
                if($data['retCode'] == 0){
                    $result[$orgCode] = $data['data'];
                }
            }
        }

        return $result;
    }


    private static function curlPost($curl, $url){
        $res = $curl->post($url, true);
        if($res === false){
            throw new \Exception('调用extapi出错:' . $curl->response);
        }
        return json_decode($res,true);
    }

    private static function curlGet($curl, $url){
        $res = $curl->get($url, true);
        if($res === false){
            throw new \Exception('调用extapi(' . $url . ')出错:' . $curl->response);
        }
        return json_decode($res,true);
    }

    /**
     * 获取合同授权数量
     * @param $orgcode
     * @param $contractCode
     * @return array|null
     * @throws \Exception
     */
    public static function getContractAuthorizeCount($orgcode, $contractCode)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if (empty($appCfg)) {
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp . "#" . $appsecret);
        $siteUrl = rtrim($appCfg['url'], '/');
        $param = [
            'r'       => 'project-auth/get-contract-authorize-count',
            'appid'   => $appCfg["appId"],
            't'       => $nowtimestamp,
            'sign'    => $sign,
            'orgcode' => $orgcode,
            'contractCode' => $contractCode,
        ];
        $res = self::curlGet($curl, $siteUrl . '?' . http_build_query($param));

        if ($res['retCode'] == 0) {
            return $res['data'];
        }

        return [];
    }

}

